#include <iostream>
#include "Common.hpp"
#include "InerAddr.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " <server_ip> <server_port>" << std::endl;
}

int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    // 1. 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "create socket failed" << std::endl;
        exit(SOCKET_ERR);
    }  

    // 2. bind码？不需要，随机方式选择端口号
    // 3. 直接目标服务器发起建立连接请求
    InerAddr serveraddr(server_ip, server_port);
    int n = connect(sockfd, serveraddr.NetAddrPtr(), serveraddr.NetAddrLen());
    if(n < 0)
    {
        std::cerr << "connect failed" << std::endl;
        exit(CONNECT_ERR);
    }
    
    while(true)
    {
        std::string line;
        std::cout << "Please Enter@ ";
        std::getline(std::cin, line);

        write(sockfd, line.c_str(), line.size());

        char buffer[1024];
        ssize_t size = read(sockfd, buffer, sizeof(buffer));
        if(size > 0)
        {
            buffer[size] = 0;
            std::cout << "Server echo# " << buffer << std::endl;
        }
    }

    close(sockfd);
    return 0;
}